﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Entities;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Data;
using System.Collections;
using System.Drawing;

namespace Common
{
    public static class Utilities
    {
        public static Entities.TaiKhoan User = null;
        public static Entities.ChiTietQuyen[] chitiet = null;

        public static bool Check(string tenForm, int check)
        {
            try
            {
                if (User.Administrator)
                {
                    return true;
                }

                switch (check)
                {
                    case 0:
                        {
                            foreach (Entities.ChiTietQuyen item in chitiet)
                            {
                                if (item.TenForm == tenForm && item.QuyenXem)
                                {
                                    return true;
                                }

                            }
                            break;
                        }
                    case 1:
                        {
                            foreach (Entities.ChiTietQuyen item in chitiet)
                            {
                                if (item.TenForm == tenForm && item.QuyenThem)
                                {
                                    return true;
                                }
                            }
                            break;
                        }
                    case 2:
                        {
                            foreach (Entities.ChiTietQuyen item in chitiet)
                            {
                                if (item.TenForm == tenForm && item.QuyenSua)
                                {
                                    return true;
                                }
                            }
                            break;
                        }
                    case 3:
                        {
                            foreach (Entities.ChiTietQuyen item in chitiet)
                            {
                                if (item.TenForm == tenForm && item.QuyenXoa)
                                {
                                    return true;
                                }
                            }
                            break;
                        }
                    default:
                        break;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }

        private static int pos = 0;
        private static string chuoi = string.Empty;
        public static string RemoveChar(String s)
        {

            try
            {
                Pos(s, ',');
                if (pos != -1)
                {
                    while (pos != -1)
                    {
                        StringBuilder buf = new StringBuilder(chuoi.Length - 1);
                        buf.Append(chuoi.Substring(0, pos)).Append(chuoi.Substring(pos + 1));
                        chuoi = buf.ToString();
                        Pos(chuoi, ',');
                    }
                }
            }
            catch { chuoi = s; }
            return chuoi;
        }
        public static void CountDatagridview(DataGridView dgv)
        {
            try
            {
                if (dgv.RowCount <= 0)
                { return; }
                int stt = 0;
                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    stt = stt + 1;
                    dgv.Rows[i].Cells["HanhDong"].Value = stt;
                }
                //dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
        }
        public static byte[] GetImage(string linksRoot)
        {
            byte[] image = null;
            try
            {
                Bitmap bmp = new Bitmap(linksRoot);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] manganh = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(manganh, 0, Convert.ToInt32(ms.Length));
                image = manganh;
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                image = null;
            }
            return image;
        }

        private static void Pos(string s, char kitu)
        {
            chuoi = s;
            pos = s.IndexOf(kitu);
        }
        public static string Encrypt(string key, string toEncrypt)
        {
            string rt = "";
            try
            {
                byte[] keyArray;
                byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
                tdes.Key = keyArray;
                tdes.Mode = CipherMode.ECB;
                tdes.Padding = PaddingMode.PKCS7;
                ICryptoTransform cTransform = tdes.CreateEncryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                rt = System.Convert.ToBase64String(resultArray, 0, resultArray.Length);
            }
            catch (Exception ex)
            { string s = ex.Message; rt = ""; }
            return rt;
        }

        public static string Decrypt(string key, string toDecrypt)
        {
            string rt = "";
            try
            {
                byte[] keyArray;
                byte[] toEncryptArray = System.Convert.FromBase64String(toDecrypt);
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
                tdes.Key = keyArray;
                tdes.Mode = CipherMode.ECB;
                tdes.Padding = PaddingMode.PKCS7;
                ICryptoTransform cTransform = tdes.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                rt = UTF8Encoding.UTF8.GetString(resultArray);
            }
            catch (Exception ex)
            { string s = ex.Message; rt = ""; }
            return rt;
        }

        public static Boolean CheckFile(string sFileName)
        {
            Boolean kt = false;
            try
            {
                string link = System.Windows.Forms.Application.StartupPath.ToString() + sFileName;
                if (System.IO.File.Exists(link) == true)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            { string s = ex.Message; kt = false; }
            return kt;
        }

        public static void CreateDirectory(string links)
        {
            try
            {
                if (System.IO.Directory.Exists(links) == false)
                {
                    Directory.CreateDirectory(links);
                }
            }
            catch (Exception ex)
            { string s = ex.Message; }
        }

        public static Boolean DeleteFile(string sFileName)
        {
            Boolean kt = false;
            try
            {
                string link = System.Windows.Forms.Application.StartupPath.ToString() + sFileName;
                FileInfo fi;
                if (System.IO.File.Exists(link) == true)
                {
                    fi = new FileInfo(link);
                    fi.Delete();
                    kt = true;
                }
                else
                {
                    kt = false;
                }
            }
            catch (Exception ex)
            { ex.Message.ToString(); kt = false; }
            return kt;
        }

        public static string GetDateID(string data)
        {
            string thoigian = "";
            try
            {
                string[] tam = data.Split('/');
                string ngay = tam[0].ToString();
                string thang = tam[1].ToString();
                string nam = tam[2].ToString().Substring(0, 4).ToString();
                thoigian = ngay + thang + nam;
            }
            catch (Exception ex)
            { string s = ex.Message; thoigian = ""; }
            return thoigian;
        }

        public static string GetID(string hoadon, string strChuoi, string ngay, string diadiem)
        {
            string tra = "";
            try
            {
                int i = strChuoi.LastIndexOf("_");
                int ID = System.Convert.ToInt32(strChuoi.Substring(i + 1));
                ID = ID + 1;
                string IDcuoi = ID.ToString();
                if (IDcuoi.Length == 1)
                { IDcuoi = "000" + IDcuoi; }
                else
                {
                    if (IDcuoi.Length == 2)
                    { IDcuoi = "00" + IDcuoi; }
                    else
                    {
                        if (IDcuoi.Length == 3)
                        { IDcuoi = "0" + IDcuoi; }
                    }
                }
                string tralai = hoadon + "/" + diadiem + "/" + GetDateID(ngay) + "_" + IDcuoi;
                return tralai;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public static string ProcessID(string strChuoi)
        {
            try
            {
                int i = strChuoi.LastIndexOf("_");
                int ID = System.Convert.ToInt32(strChuoi.Substring(i + 1));
                string IDdau = strChuoi.Substring(0, i);
                ID = ID + 1;
                string IDcuoi = ID.ToString();
                if (IDcuoi.Length == 1) IDcuoi = "000" + IDcuoi;
                else if (IDcuoi.Length == 2) IDcuoi = "00" + IDcuoi;
                else if (IDcuoi.Length == 3) IDcuoi = "0" + IDcuoi;

                return IDdau + "_" + IDcuoi;
            }
            catch
            {
                return null;
            }
        }

        public static string ProcessRandomID(string strChuoi)
        {
            try
            {
                string IDcuoi = strChuoi.ToString();
                if (IDcuoi.Length == 1) IDcuoi = "000" + IDcuoi;
                else if (IDcuoi.Length == 2) IDcuoi = "00" + IDcuoi;
                else if (IDcuoi.Length == 3) IDcuoi = "0" + IDcuoi;

                return IDcuoi;
            }
            catch
            {
                return null;
            }
        }

        public static string XuLy(int viet, string chuoi)
        {
            string tralai = "";
            try
            {
                if (viet == 1)
                {
                    string dd = DateTime.Parse(chuoi.ToString()).Day.ToString();
                    if (dd.Length == 1)
                    {
                        dd = "0" + dd;
                    }
                    string mm = DateTime.Parse(chuoi.ToString()).Month.ToString();
                    if (mm.Length == 1)
                    {
                        mm = "0" + mm;
                    }
                    string yyyy = DateTime.Parse(chuoi.ToString()).Year.ToString();
                    tralai = mm + "/" + dd + "/" + yyyy;
                }
                if (viet == 2)
                {
                    string dd = DateTime.Parse(chuoi.ToString()).Day.ToString();
                    if (dd.Length == 1)
                    {
                        dd = "0" + dd;
                    }
                    string mm = DateTime.Parse(chuoi.ToString()).Month.ToString();
                    if (mm.Length == 1)
                    {
                        mm = "0" + mm;
                    }
                    string yyyy = DateTime.Parse(chuoi.ToString()).Year.ToString();
                    tralai = dd + "/" + mm + "/" + yyyy;
                }
                if (viet == 3)
                {
                    string dd = DateTime.Parse(chuoi.ToString()).Day.ToString();
                    if (dd.Length == 1)
                    {
                        dd = "0" + dd;
                    }
                    string mm = DateTime.Parse(chuoi.ToString()).Month.ToString();
                    if (mm.Length == 1)
                    {
                        mm = "0" + mm;
                    }
                    string yyyy = DateTime.Parse(chuoi.ToString()).Year.ToString();
                    tralai = dd + mm + yyyy;
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message.ToString();
                tralai = "";
            }
            return tralai;
        }

        public static string MyDateConversion(string data)
        {
            string thoigian = "";
            try
            {
                string[] tam = data.Split('/');
                int ngay = int.Parse(tam[0].ToString());
                int thang = int.Parse(tam[1].ToString());
                int nam = int.Parse(tam[2].ToString().Substring(0, 4).ToString());
                if (ngay > 31 || ngay < 1)
                {
                    thoigian = "";
                }
                else
                {
                    if (thang > 12 || thang < 1)
                    {
                        thoigian = "";
                    }
                    else
                    {
                        if (nam > 9998 || nam < 1900)
                        {
                            thoigian = "";
                        }
                        else
                        {
                            thoigian = thang + "/" + ngay + "/" + nam;
                        }
                    }
                }
            }
            catch (Exception ex)
            { string s = ex.Message; thoigian = ""; }
            return thoigian;
        }
        public static void XuLyComboBox(ComboBox cbb, object[] obj, string display, string value)
        {
            try
            {
                if (obj.Length == 0)
                {
                    cbb.DataSource = null;
                }
                else
                {
                    cbb.DataSource = obj;
                    cbb.DisplayMember = display;
                    cbb.ValueMember = value;
                    cbb.SelectedIndex = 0;
                }
            }
            catch
            {
            }
        }
        public static string FormatMoney(string money)
        {
            if (double.Parse(money) >= 0 && double.Parse(money) < 10)
                return money;
            string str = "";
            try
            {
                if (double.Parse(money) < 0)
                    str = String.Format("{0,-0:0,0}", double.Parse(money));
                else
                    str = String.Format("{0:0,0}", double.Parse(money));
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                str = "";
            }
            return str;
        }

        public static Entities.HangHoa[] CheckGoiHang(Entities.HangHoa[] hh1, Entities.GoiHang[] goihang, Entities.ChiTietGoiHang[] chitietgoihang)
        {
            try
            {
                ArrayList array = new ArrayList();
                foreach (Entities.GoiHang item in goihang)
                {
                    int sotang = 0;
                    foreach (Entities.ChiTietGoiHang item1 in chitietgoihang)
                    {
                        if (item.MaGoiHang == item1.MaGoiHang)
                        {
                            sotang++;
                            foreach (Entities.HangHoa item2 in hh1)
                            {
                                if (item1.MaHangHoa == item2.MaHangHoa)
                                {
                                    sotang--;
                                    break;
                                }
                            }
                            if (sotang != 0)
                                break;
                        }
                    }
                    if (sotang == 0)
                    {
                        Entities.HangHoa hh = new Entities.HangHoa();
                        hh.MaHangHoa = item.MaGoiHang;
                        hh.TenHangHoa = item.TenGoiHang;
                        hh.MaThue = "";
                        hh.GiaBanBuon = item.GiaBanBuon;
                        hh.GiaBanLe = item.GiaBanLe;
                        hh.GiaNhap = item.GiaNhap;
                        array.Add(hh);
                    }
                }
                return (Entities.HangHoa[])array.ToArray(typeof(Entities.HangHoa));
            }
            catch
            {
                return new Entities.HangHoa[0];
            }
        }


        public static string RandomID()
        {
            Random rd = new Random();
            int i = rd.Next(1000, 9999);
            return i.ToString();
        }

        public static byte[] GetArrayByte(string linkRoot)
        {
            byte[] img = null;
            try
            {
                Bitmap bitmap = new Bitmap(linkRoot);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                img = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(img, 0, Convert.ToInt32(ms.Length));

            }
            catch (Exception ex)
            { string s = ex.Message; img = null; }
            return img;
        }

        public static System.Drawing.Image GetImage(byte[] byteArray)
        {
            if (byteArray == null)
            {
                return null;
            }
            using (var stream = new MemoryStream(byteArray))
            {
                return System.Drawing.Image.FromStream(stream);
            }
        }

        #region H
        //Tạo mã băm bằng thuật toán SHA1
        public static string EncodeToSHA1(this string value)
        {
            UnicodeEncoding uEncode = new UnicodeEncoding();
            byte[] byteValue = uEncode.GetBytes(value);
            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
            byte[] hash = sha1.ComputeHash(byteValue);
            string str = Convert.ToBase64String(hash);
            return str;
        }

        //Tạo mã băm bằng thuật toán SHA256
        public static string EncodeToSHA256(this string value)
        {
            UnicodeEncoding uEncode = new UnicodeEncoding();
            byte[] byteValue = uEncode.GetBytes(value);
            SHA256CryptoServiceProvider sha1 = new SHA256CryptoServiceProvider();
            byte[] hash = sha1.ComputeHash(byteValue);
            string str = Convert.ToBase64String(hash);
            return str;
        }

        //Tạo mã băm bằng thuật toán SHA384
        public static string EncodeToSHA384(this string value)
        {
            UnicodeEncoding uEncode = new UnicodeEncoding();
            byte[] byteValue = uEncode.GetBytes(value);
            SHA384CryptoServiceProvider sha1 = new SHA384CryptoServiceProvider();
            byte[] hash = sha1.ComputeHash(byteValue);
            string str = Convert.ToBase64String(hash);
            return str;
        }


        //Tạo mã băm bằng thuật toán SHA512
        public static string EncodeToSha512(this string value)
        {
            UnicodeEncoding uEncode = new UnicodeEncoding();
            byte[] byteValue = uEncode.GetBytes(value);
            SHA512CryptoServiceProvider sha1 = new SHA512CryptoServiceProvider();
            byte[] hash = sha1.ComputeHash(byteValue);
            string str = Convert.ToBase64String(hash);
            return str;
        }


        //Tạo mã băm bằng thuật toánMD5
        public static string EncodeToMD5(this string value)
        {
            UnicodeEncoding uEncode = new UnicodeEncoding();
            byte[] byteValue = uEncode.GetBytes(value);
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] hash = md5.ComputeHash(byteValue);
            string str = Convert.ToBase64String(hash);
            return str;
        }
        #endregion
    }
}
